<template>
  <div class='index-container' v-bind:style='{ minHeight: `calc(100vh - ${navBarHeight}px)` }'>
    <van-nav-bar
:title="'选手投票丨' + pidNum + titleName"
left-arrow
@click-left='onClickLeft'
ref='nav'
     @click-right="testshareUrlToZH">
         <template #right>
            <img src="../../assets/img/rightArr.png"  style="width: 20px;height: 20px;">
          </template>
     </van-nav-bar>
    <div class='warpper' v-bind:style='{ marginTop: `${navBarHeight}px` }'>
      <van-loading size='40px' v-if='isloadig === false'>加载中...</van-loading>
      <div class='' v-else>
        <div class='details'>
          <div class='info'>
            <div class='info-top ov'>
              <span class='name fl line2'>{{ competitorInfo.id }}{{ competitorInfo.name }} </span>
              <div class='btn fr'>票数:{{ competitorInfo.vote_num }}</div>
            </div>
            <div class='fs-30'>员工编号：{{ competitorInfo.employee_number }}</div>
            <div class='fs-30'>所属单位：{{ bankName }}<sapn v-if="competitorInfo.department_name">-</sapn>{{ competitorInfo.department_name }}</div>
            <div class='fs-30'>参赛类型：{{ cateName }}</div>
            <div class='fs-30 ov'>
              参赛宣言：{{ competitorInfo.declaration }}
            </div>
          </div>
          <div class='info-two'>
            {{ competitorInfo.introduction }}
          </div>
        </div>
        <div class='details-title'>
          <span class=''>{{ competitorInfo.entries_name }}</span>
        </div>
        <div class='details-two'>
          <div class='de-video'>
            <div ref='player' class='player'></div>
          </div>
        </div>
        <div class='button'>
          <div class='vote-btn on' v-if='competitorInfo.is_enable == 0'>
            投票
          </div>
          <div class='vote-btn ' v-if='competitorInfo.is_enable == 1 && competitorInfo.is_enable_vote == 0'>
            今日已投票
          </div>
          <div class='vote-btn' @click='getVote( competitorInfo )' v-if='competitorInfo.is_enable == 1 && competitorInfo.is_enable_vote == 1'>投票
          </div>
        </div>
      </div>
    </div>
    <van-popup v-model='show'>
      <div class='search-popup'>
        <div class='title'>
          <div class='span1' v-if='isType == 1'>恭喜！</div>
          <div class='span1' v-if='isType == 2'>抱歉....</div>
          <div class='' v-if='isType == 3'>
            <div class='span pt33'>抱歉</div>
            <div class='pb30'>投票已截止</div>
          </div>
          <div class='' v-if='isType == 1'>
            投票成功！
            <div class='mt5'>谢谢您的支持</div>
          </div>
          <!-- 不能投 -->
          <div class='' v-if='isType == 2'>
            您今日已投过该作品
            <div class='mt5'>看看别的吧</div>
          </div>
        </div>
        <div class='img'>
          <!-- 没找到 -->
          <img src='../../assets/img/vote/资源18.png' alt='' v-if='isType == 3' />
          <!-- 恭喜 -->
          <img src='../../assets/img/vote/资源20.png' alt='' v-if='isType == 1' />
          <!-- 不能投 -->
          <img src='../../assets/img/vote/资源19.png' alt='' v-if='isType == 2' />
        </div>
        <div class='confirm' @click='hiddenShow'>确定</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import debounce from 'lodash.debounce' // 防抖插件
import { getCompetitorRead, Vote } from '@/api/user.js'
import { fillNumber } from '../../utils/index'
import DPlayer from 'dplayer'
import MobileJS from '@/utils/MobileJS-1.0.6'
import { Base64 } from 'js-base64'
// import { encode, decode } from 'js-base64';
export default {
  name: 'Competition',
  components: {
  },
  data() {
    return {
      navBarHeight: 0,
      pid: '',
      competitorInfo: {},
      initialized: false,
      playerOptions: {},
      images: [],
      show: false,
      isType: 0,
      bankName: '',
      titleName: '',
      pidNum: '',
      isloadig: false,
      cateName: '',
      bs64Img: ''
    }
    //
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player
    }
  },
  mounted() {
    console.log(location.href, 'location.href')
    this.navBarHeight = this.$refs.nav.$el.offsetHeight
  },
  created() {
    this.pid = this.$route.query.id
     let numLen = this.pid.toString().length
    this.pidNum = fillNumber(3, this.pid)
    this.titleName = this.$route.query.name
    this.getDetails()
  },

  methods: {
    // 异步执行
    imageUrlToBase64(imageUrl) {
    	// 一定要设置为let，不然图片不显示
    	const image = new Image()

    	// 解决跨域问题
    	image.setAttribute('crossOrigin', 'anonymous')
    	image.src = imageUrl
    	// image.onload为异步加载
    	image.onload = () => {
    		var canvas = document.createElement('canvas')
    		canvas.width = image.width
    		canvas.height = image.height
    		var context = canvas.getContext('2d')
    		context.drawImage(image, 0, 0, image.width, image.height)
    		var quality = 0.8
    		// 这里的dataurl就是base64类型
    		var dataURL = canvas.toDataURL('image/jpeg', quality)// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
        this.bs64Img =  dataURL
    	}
    },
    // 分享到招呼
    testshareUrlToZH() {
    	var title = '选手' + this.competitorInfo.id + this.competitorInfo.name
    	var subject = '快来投票吧'
    	var url = location.href

      var str= this.bs64Img;
      var pos = str.indexOf(',');
      var result = str.substring(pos+1,str.length);
      const config = {
        itemType: '3',
        webNavBar: 'Y',
        webToolBar: 'Y',
        name: '智慧工平台',
        webUrl: url,
        quitPage: 'Y'
      }
      const webConfig = encodeURIComponent(Base64.encode(JSON.stringify(config)))
      var sessionId = ''
    	var option = {
    	    callback: {},
    	    asyncData: '',
    	    title: title,
    	    image: result,
    	    subject: subject,
    	    url: `CMBMobileOA:///?sysId=ZHTK&webConfig=${webConfig}`,
        sessionId: sessionId
    	}
      console.log(option, 'option传值')
    	MobileJS.shareUrlToZH(option)
    },
    onPlayerReadied(item, index) {
      if (this.initialized) {
        this.initialized = true
      }
    },
    // record current time
    onTimeupdate(e) {
      console.log('currentTime', e.cache_.currentTime)
    },
    onClickLeft() {
      if (location.href.indexOf('data') !== -1) {
        this.$router.push('/home')
      } else {
        this.$router.go(-1)
      }
    },
    // 获取赛区详情
    getDetails() {
      const that = this
      const param = {
        id: that.pid
      }
      getCompetitorRead(param).then(res => {
        this.isloadig = true
        if (res.code === 200) {
          const datas = res.data
          that.competitorInfo = datas
          let numLen =  datas.id.toString().length
          that.competitorInfo.id = fillNumber(numLen, datas.id)
          this.bankName = datas.bank.name
          this.cateName = datas.category.name
          if (that.competitorInfo.images) {
            that.images = that.competitorInfo.images.split('|')
          }
          const playerOptions = {
            poster: datas.image, // 你的封面地址
            language: 'zh-CN',
            type: 'video/mp4',
            src: datas.video,
            height: 211 // 视频框的高度
          }
          var imageUrl = that.competitorInfo.image
          this.imageUrlToBase64(imageUrl)
          this.initPlayer(playerOptions)
        }
      })
    },

    initPlayer(playerOptions) {
      this.$nextTick(() => {
        // 初始化播放器
        const dp = new DPlayer({
          container: this.$refs.player,
          theme: '#FADFA3',
          lang: 'zh-cn',
          video: {
            pic: playerOptions.poster,
            url: playerOptions.src,
            type: 'auto',
            pluginOptions: {
              hls: {
                autoStartLoad: true,
                startPosition: -1
              }
            }
          }
        })

        document.getElementsByClassName('dplayer-setting')[0].style.display = 'none'
        document.getElementsByClassName('dplayer-icon dplayer-full-in-icon')[0].style.display = 'none'
      })
    },

    hiddenShow() {
      this.show = false
    },
    getVote: debounce(function(item) {
      const param = {
        id: this.pid
      }
      Vote(param).then(res => {
        if (res.code === 200) {
          this.isType = 1
          this.show = !this.show
          item.vote_num++
          item.is_enable_vote = 0
        } else if (res.code === 2000) {
          if (res.status !== -1) {
            this.isType = 2
            this.show = !this.show
          } else {
            this.$toast(res.msg)
          }
        } else {
          this.$toast(res.msg)
        }
      })
    }, 300)
  }
}
</script>

<style lang='scss' scoped>
@import '../../assets/css/video.scss';
@import './css/detail.scss';

.player {
  height: 211px;
}


</style>
